package com.tutk.P2PCam264;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.tutk.IOTC.AVIOCTRLDEFs;
import com.tutk.IOTC.AVIOCTRLDEFs.SMsgAVIoctrlGetSupportStreamReq;
import com.tutk.IOTC.Camera;
import com.tutk.IOTC.IRegisterIOTCListener;
import com.tutk.IOTC.Packet;
import com.tutk.Logger.Glog;
import com.tutk.agza.AgzaPushUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import cn.innosmart.aq.R;
import cn.innosmart.aq.view.activity.BoxListActivity;

public class MainActivity extends AppCompatActivity implements IRegisterIOTCListener {

    public static final int CAMERA_MAX_LIMITS = 4;
    private static final int Build_VERSION_CODES_ICE_CREAM_SANDWICH = 14;
    private static final int REQUEST_CODE_CAMERA_ADD = 0;
    private static final int REQUEST_CODE_CAMERA_VIEW = 1;
    private static final int REQUEST_CODE_CAMERA_EDIT = 2;
    private static final int REQUEST_CODE_CAMERA_HISTORY = 3;
    private static final int CTX_MENU_ITEM_RECONNECT = Menu.FIRST;
    private static final int CTX_MENU_ITEM_EDIT_CAM = Menu.FIRST + 1;
    private static final int CTX_MENU_ITEM_VIEW_EVENT = Menu.FIRST + 2;
    private static final int CTX_MENU_ITEM_VIEW_SNAPSHOT = Menu.FIRST + 3;
    private static final int CTX_MENU_ITEM_REMOVE_CAM = Menu.FIRST + 4;
    private static final int OPT_MENU_ITEM_ADD_CAM = Menu.FIRST;
    private static final int OPT_MENU_ITEM_ABOUT = Menu.FIRST + 1;
    private static final int OPT_MENU_ITEM_EXIT = Menu.FIRST + 2;
    private static final int idCmd_AddCamera = 7000;
    private static final int idCmd_LiveView = 7001;
    public static int nShowMessageCount = 0;
    public static String token = null;
    public static boolean noResetWiFi = true;
    public static List<MyCamera> CameraList = new ArrayList<MyCamera>();
    public static List<DeviceInfo> DeviceList = Collections.synchronizedList(new ArrayList<DeviceInfo>());
    public static long startTime = 0;
    private final int CONTEXT_MENU_ID = 1;
    //	private Timer timer = new Timer(true);
    // public String[] allFiles;
    // private String SCAN_PATH;
    // private static final String FILE_TYPE = "image/*";
    // private MediaScannerConnection conn;
    private DeviceListAdapter adapter;
    private IconContextMenu iconContextMenu = null;
    private ListView listView;
    private View addDeviceView;
    private DeviceInfo selectedDevice = null;
    private MyCamera selectedCamera = null;
    private int mCustomURL_CmdID;
    private String mstrUid_FromCustomURL;
    private ResultStateReceiver resultStateReceiver;
    private IntentFilter filter;
    private ThreadTPNS thread;
    private ThreadReconnect m_threadReconnect = null;
    private ProgressDialog progressDialog;
    private AdapterView.OnItemLongClickListener listViewOnItemLongClickListener = new AdapterView.OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View v, int position, long id) {

            if (position < DeviceList.size() && position < CameraList.size()) {

                selectedCamera = CameraList.get(position);
                selectedDevice = DeviceList.get(position);

                initContextMenu();
                iconContextMenu.createMenu("").show();

                return true;
            }

            return false;
        }
    };
    private AdapterView.OnItemClickListener listViewOnItemClickListener = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {

            if (position < DeviceList.size()) {

                if (!DeviceList.get(position).Online) {
                    return;
                }

                final DeviceInfo dev = DeviceList.get(position);
                if (dev != null && "admin".equals(dev.View_Password)) {
                    final MyCamera cam = CameraList.get(position);

                    Builder dialog = new Builder(new ContextThemeWrapper(MainActivity.this, R.style.HoloAlertDialog));
                    dialog.setMessage(MainActivity.this.getResources().getString(R.string.dialog_mod_initpwd));
                    dialog.setPositiveButton(MainActivity.this.getResources().getString(R.string.ok), new OnClickListener() {

                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            Builder builder = new Builder(new ContextThemeWrapper(MainActivity.this, R.style.HoloAlertDialog));
                            final AlertDialog dlg = builder.create();
                            dlg.setTitle(R.string.dialog_ModifySecurityCode);
                            dlg.setIcon(android.R.drawable.ic_menu_more);

                            LayoutInflater inflater = dlg.getLayoutInflater();
                            View view = inflater.inflate(R.layout.modify_security_code, null);
                            dlg.setView(view);

                            final EditText edtOldPassword = (EditText) view.findViewById(R.id.edtOldPassword);
                            final EditText edtNewPassword = (EditText) view.findViewById(R.id.edtNewPassword);
                            final EditText edtConfirmPassword = (EditText) view.findViewById(R.id.edtConfirmPassword);
                            Button btnOK = (Button) view.findViewById(R.id.btnOK);
                            Button btnCancel = (Button) view.findViewById(R.id.btnCancel);
                            btnOK.setOnClickListener(new View.OnClickListener() {

                                @Override
                                public void onClick(View v) {

                                    String oldPwd = edtOldPassword.getText().toString();
                                    String newPwd = edtNewPassword.getText().toString();
                                    String confirmPwd = edtConfirmPassword.getText().toString();

                                    if (oldPwd.length() == 0 || newPwd.length() == 0 || confirmPwd.length() == 0) {
                                        Toast.makeText(MainActivity.this, getText(R.string.tips_all_field_can_not_empty).toString(), Toast.LENGTH_SHORT).show();
                                        return;
                                    }

                                    if (!oldPwd.equalsIgnoreCase(dev.View_Password)) {
                                        Toast.makeText(MainActivity.this, getText(R.string.tips_old_password_is_wrong).toString(), Toast.LENGTH_SHORT).show();
                                        return;
                                    }

                                    if (!newPwd.equalsIgnoreCase(confirmPwd)) {
                                        Toast.makeText(MainActivity.this, getText(R.string.tips_new_passwords_do_not_match).toString(), Toast.LENGTH_SHORT).show();
                                        return;
                                    }

                                    if (cam != null) {
                                        DatabaseManager manager = new DatabaseManager(MainActivity.this);
                                        SQLiteDatabase db = manager.getReadableDatabase();
                                        ContentValues values = new ContentValues();
                                        values.put("view_pwd", newPwd);

                                        dev.View_Password = newPwd;

                                        db.update(DatabaseManager.TABLE_DEVICE, values, "_id = '" + dev.DBID + "'", null);

                                        db.close();

                                        cam.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SETPASSWORD_REQ, AVIOCTRLDEFs.SMsgAVIoctrlSetPasswdReq.parseContent(oldPwd, newPwd));
                                    }

                                    dlg.dismiss();
                                }
                            });

                            btnCancel.setOnClickListener(new View.OnClickListener() {

                                @Override
                                public void onClick(View v) {
                                    dlg.dismiss();
                                }
                            });

                            dlg.show();
                        }
                    });

                    dialog.create().show();
                } else {
                    Bundle extras = new Bundle();
                    extras.putString("dev_uid", DeviceList.get(position).UID);
                    extras.putString("dev_uuid", DeviceList.get(position).UUID);
                    extras.putString("dev_nickname", DeviceList.get(position).NickName);
                    extras.putString("conn_status", DeviceList.get(position).Status);
                    extras.putString("view_acc", DeviceList.get(position).View_Account);
                    extras.putString("view_pwd", DeviceList.get(position).View_Password);
                    extras.putInt("camera_channel", DeviceList.get(position).ChannelIndex);

                    Intent intent = new Intent();
                    intent.putExtras(extras);
                    intent.setClass(MainActivity.this, LiveViewActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_CAMERA_VIEW);
                }
            } else {

                if (CameraList.size() < CAMERA_MAX_LIMITS) {
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, AddDeviceActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_CAMERA_ADD);
                }
            }
        }
    };
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            Bundle bundle = msg.getData();
            String requestDevice = bundle.getString("requestDevice");

            byte[] data = bundle.getByteArray("data");
//			int i = 0;

            DeviceInfo device = null;
            MyCamera camera = null;

            for (int i = 0; i < DeviceList.size(); i++) {

                if (DeviceList.get(i).UUID.equalsIgnoreCase(requestDevice)) {
                    device = DeviceList.get(i);
                    break;
                }
            }

            for (int i = 0; i < CameraList.size(); i++) {

                if (CameraList.get(i).getUUID().equalsIgnoreCase(requestDevice)) {
                    camera = CameraList.get(i);
                    break;
                }
            }

            switch (msg.what) {

                case Camera.CONNECTION_STATE_CONNECTING:

                    if (camera != null) {
                        if (!camera.isSessionConnected() || !camera.isChannelConnected(0)) {
                            if (device != null) {
                                device.Status = getText(R.string.connstus_connecting).toString();
                                device.Online = false;

                            }
                        }
                    }

                    break;

                case Camera.CONNECTION_STATE_CONNECTED:

                    if (camera != null) {
                        if (camera.isSessionConnected() && camera.isChannelConnected(0)) {
                            if (device != null) {
                                device.Status = getText(R.string.connstus_connected).toString();
                                device.Online = true;
                                device.connect_count = 0;
                                if (m_threadReconnect != null) {
                                    m_threadReconnect.stopCheck = true;
                                    m_threadReconnect.interrupt();
                                    m_threadReconnect = null;
                                    device.connect_count++;
                                }
                                if (device.ChangePassword) {
                                    device.ChangePassword = false;
                                    ThreadTPNS ThreadTPNS = new ThreadTPNS(MainActivity.this, device.UID, 0);
                                    ThreadTPNS.start();
                                    DatabaseManager manager = new DatabaseManager(MainActivity.this);
                                    manager.delete_remove_list(device.UID);
                                }

                            }
                        }
                    }

                    break;

                case Camera.CONNECTION_STATE_UNKNOWN_DEVICE:

                    if (device != null) {
                        device.Status = getText(R.string.connstus_unknown_device).toString();
                        device.Online = false;

                    }

                    break;

                case Camera.CONNECTION_STATE_DISCONNECTED:
                    // no Use
                    if (device != null) {
                        device.Status = getText(R.string.connstus_disconnect).toString();
                        device.Online = false;

                        if (device.connect_count < 3 && noResetWiFi) {
                            if (m_threadReconnect == null) {
                                startTime = System.currentTimeMillis();
                                m_threadReconnect = new ThreadReconnect(camera, device);
                                m_threadReconnect.start();
                                device.connect_count++;
                            }
//						reconnect(camera,device);
                        }
                    }

                    if (camera != null) {
                        camera.disconnect();
                    }

                    break;

                case Camera.CONNECTION_STATE_TIMEOUT:

                    if (device != null) {
                        device.Status = getText(R.string.connstus_disconnect).toString();
                        device.Online = false;

                        if (device.connect_count < 3 && noResetWiFi) {
                            if (m_threadReconnect == null) {
                                startTime = System.currentTimeMillis();
                                m_threadReconnect = new ThreadReconnect(camera, device);
                                m_threadReconnect.start();
                                device.connect_count++;
                            }
//						reconnect(camera,device);
                        } else if (device.connect_count >= 3) {
                            camera.disconnect();
                        }
                    }

                    break;

                case Camera.CONNECTION_STATE_WRONG_PASSWORD:

                    if (device != null) {
                        device.Status = getText(R.string.connstus_wrong_password).toString();
                        device.Online = false;
                        ThreadTPNS ThreadTPNS = new ThreadTPNS(MainActivity.this, device.UID);
                        ThreadTPNS.start();
                    }

                    if (camera != null) {
                        camera.disconnect();
                    }

                    break;

                case Camera.CONNECTION_STATE_CONNECT_FAILED:

                    if (device != null) {
                        device.Status = getText(R.string.connstus_connection_failed).toString();
                        device.Online = false;

                    }

                    break;

                case AVIOCTRLDEFs.IOTYPE_USER_IPCAM_EVENT_REPORT:

                    byte[] t = new byte[8];
                    System.arraycopy(data, 0, t, 0, 8);
                    AVIOCTRLDEFs.STimeDay evtTime = new AVIOCTRLDEFs.STimeDay(t);

                    int camChannel = Packet.byteArrayToInt_Little(data, 12);
                    int evtType = Packet.byteArrayToInt_Little(data, 16);

                    if (evtType != AVIOCTRLDEFs.AVIOCTRL_EVENT_MOTIONPASS && evtType != AVIOCTRLDEFs.AVIOCTRL_EVENT_IOALARMPASS)

                        showNotification(device, camChannel, evtType, evtTime.getTimeInMillis());

                    break;

                case AVIOCTRLDEFs.IOTYPE_USER_IPCAM_DEVINFO_RESP:

                    int total = Packet.byteArrayToInt_Little(data, 40);
                    if (total == -1 && camera != null && camera.getSDCardFormatSupported(0) && device != null && device.ShowTipsForFormatSDCard)
                        showSDCardFormatDialog(camera, device);

                    break;

                case AVIOCTRLDEFs.IOTYPE_USER_IPCAM_FORMATEXTSTORAGE_RESP:

                    int result = data[4];

                    if (result == 0)
                        Toast.makeText(MainActivity.this, getText(R.string.tips_format_sdcard_success).toString(), Toast.LENGTH_SHORT).show();
                    else
                        Toast.makeText(MainActivity.this, getText(R.string.tips_format_sdcard_failed).toString(), Toast.LENGTH_SHORT).show();

                    break;
            }

            if (device != null && camera != null)
                device.Mode = camera.getSessionMode();

            adapter.notifyDataSetChanged();
            super.handleMessage(msg);
        }
    };

    public static void showAlert(Context context, CharSequence title, CharSequence message, CharSequence btnTitle) {

        Builder dlgBuilder = new Builder(context);
        dlgBuilder.setIcon(android.R.drawable.ic_dialog_alert);
        dlgBuilder.setTitle(title);
        dlgBuilder.setMessage(message);
        dlgBuilder.setPositiveButton(btnTitle, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        }).show();
    }

    public final static String getEventType(Context context, int eventType, boolean isSearch) {

        String result = "";

        switch (eventType) {
            case AVIOCTRLDEFs.AVIOCTRL_EVENT_ALL:
                result = isSearch ? context.getText(R.string.evttype_all).toString() : context.getText(R.string.evttype_fulltime_recording).toString();
                break;

            case AVIOCTRLDEFs.AVIOCTRL_EVENT_MOTIONDECT:
                result = context.getText(R.string.evttype_motion_detection).toString();
                break;

            case AVIOCTRLDEFs.AVIOCTRL_EVENT_VIDEOLOST:
                result = context.getText(R.string.evttype_video_lost).toString();
                break;

            case AVIOCTRLDEFs.AVIOCTRL_EVENT_IOALARM:
                result = context.getText(R.string.evttype_io_alarm).toString();
                break;

            case AVIOCTRLDEFs.AVIOCTRL_EVENT_MOTIONPASS:
                result = context.getText(R.string.evttype_motion_pass).toString();
                break;

            case AVIOCTRLDEFs.AVIOCTRL_EVENT_VIDEORESUME:
                result = context.getText(R.string.evttype_video_resume).toString();
                break;

            case AVIOCTRLDEFs.AVIOCTRL_EVENT_IOALARMPASS:
                result = context.getText(R.string.evttype_io_alarm_pass).toString();
                break;

            case AVIOCTRLDEFs.AVIOCTRL_EVENT_EXPT_REBOOT:
                result = context.getText(R.string.evttype_expt_reboot).toString();
                break;

            case AVIOCTRLDEFs.AVIOCTRL_EVENT_SDFAULT:
                result = context.getText(R.string.evttype_sd_fault).toString();
                break;
            case AVIOCTRLDEFs.AVIOCTRL_EVENT_FULLTIME_RECORDING:
                result = context.getText(R.string.evttype_fulltime_recording).toString();
                break;

        }

        return result;
    }

    /*@Override public void onMediaScannerConnected() { conn.scanFile(SCAN_PATH, FILE_TYPE); }
     * @Override public void onScanCompleted(String path, Uri uri) { try { if (uri != null) { Intent
     * intent = new Intent(Intent.ACTION_VIEW); //intent.setData(uri); Uri hacked_uri =
     * Uri.parse("file://" + uri.getPath()); intent.setDataAndType(hacked_uri, FILE_TYPE);
     * startActivity(intent); } } catch (Exception e) { Toast.makeText(MainActivity.this,
     * e.getMessage(), Toast.LENGTH_LONG).show(); } finally { conn.disconnect(); conn = null; } } */
    public static void check_mapping_list(Context context) {
        DatabaseManager manager = new DatabaseManager(context);
        SQLiteDatabase db = manager.getReadableDatabase();
        Cursor cursor = db.query(DatabaseManager.TABLE_DEVICE, new String[]{"dev_uid"}, null, null, null, null, null);
        if (cursor != null) {
            SharedPreferences settings = context.getSharedPreferences("Preference", 0);
            cursor.moveToFirst();
            for (int i = 0; i < cursor.getCount(); i++) {
                String uid = cursor.getString(0);
                settings.edit().putString(uid, uid).commit();
                //GCM
                ThreadTPNS ThreadTPNS = new ThreadTPNS(context, uid, 0);
                ThreadTPNS.start();
                Log.d("TPNS", "remove");
                cursor.moveToNext();

            }
            cursor.close();
        }
        db.close();
        check_remove_list(context);
    }

    public static void check_remove_list(Context context) {
        DatabaseManager manager = new DatabaseManager(context);
        SQLiteDatabase db = manager.getReadableDatabase();
        Cursor cursor = db.query(DatabaseManager.TABLE_REMOVE_LIST, new String[]{"uid"}, null, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            for (int i = 0; i < cursor.getCount(); i++) {
                String uid = cursor.getString(0);
                ThreadTPNS thread = new ThreadTPNS(context, uid);
                thread.start();
                cursor.moveToNext();

            }
            cursor.close();
        }
        db.close();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mCustomURL_CmdID = -1;


        //Agza register
        String udid = DatabaseManager.uid_Produce(MainActivity.this);
        AgzaPushUtil.registerAgza(MainActivity.this, "com.tutk.P2PCamLive", udid, Locale.getDefault().getLanguage());
        Log.d("TPNS", "register");

        //Agza syncmapping
        List<String> UIDList = new ArrayList<String>();
        for (MyCamera camera : CameraList) {
            UIDList.add(camera.getUID());
        }
        AgzaPushUtil.syncMapping(MainActivity.this, UIDList, "com.tutk.P2PCamLive", udid);
        Log.d("TPNS", "Main syncmapping");


        Intent tIntent = this.getIntent();
        String new_uid = tIntent.getStringExtra("tip");
        if (new_uid != null && new_uid.length() == 20) {
            Builder builder = new Builder(MainActivity.this);
            builder.setTitle(getText(R.string.tip));
            builder.setMessage(getText(R.string.setup_uid_to_device) + "\n" + new_uid);
            builder.setPositiveButton(getText(R.string.ok), new OnClickListener() {

                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    arg0.dismiss();
                }
            });
            builder.create().show();
        }

        String tSchema = tIntent.getScheme();
        Glog.I("p2pcamlive", "MainActivity.onCreate... tSchema:\"" + ((tSchema == null) ? "(null)" : tSchema) + "\"");
        if (tSchema != null && tSchema.equals("p2pcamlive")) {

            Uri myURI = tIntent.getData();
            if (myURI != null) {
                Glog.I("p2pcamlive", "MainActivity.onCreate... myURI:\"" + myURI.toString() + "\"");
                if (myURI != null) {
                    String strUri = myURI.toString();
                    int nIdx_ValidURI = strUri.indexOf("com.tutk.p2pcamlive?");
                    if (0 <= nIdx_ValidURI) {

                        String strQueryParameterCP = strUri.substring(nIdx_ValidURI + "com.tutk.p2pcamlive?".length());
                        // p2pcamlive://com.tutk.p2pcamlive?tabIdx:0
                        // 0: Camera list
                        // 1: Event list (NOT support on Android UI)
                        //
                        int nIdx_Parameter = strQueryParameterCP.indexOf("tabIdx:");
                        if (0 <= nIdx_Parameter) {
                            String strTabIndex = strQueryParameterCP.substring(nIdx_Parameter + "tabIdx:".length());

                            Glog.I("p2pcamlive", "CameraList count:" + CameraList.size() + " Jump to Event list!");
                        }

                        // p2pcamlive://com.tutk.p2pcamlive?addDev:XXXXXXXXXXXXXXXXXXXX
                        //
                        nIdx_Parameter = strQueryParameterCP.indexOf("addDev:");
                        if (0 <= nIdx_Parameter) {
                            String strUid = strQueryParameterCP.substring(nIdx_Parameter + "addDev:".length());

                            Glog.I("p2pcamlive", "CameraList count:" + CameraList.size() + " Add Camera UID:\"" + strUid + "\"");
                            mCustomURL_CmdID = idCmd_AddCamera;
                            mstrUid_FromCustomURL = strUid;
                        }

                        // p2pcamlive://com.tutk.p2pcamlive?liveView:XXXXXXXXXXXXXXXXXXXX
                        //
                        nIdx_Parameter = strQueryParameterCP.indexOf("liveView:");
                        if (0 <= nIdx_Parameter) {
                            String strUid = strQueryParameterCP.substring(nIdx_Parameter + "liveView:".length());

                            Glog.I("p2pcamlive", "CameraList count:" + CameraList.size() + " Live view UID:\"" + strUid + "\"");
                            mCustomURL_CmdID = idCmd_LiveView;
                            mstrUid_FromCustomURL = strUid;

                            handler.postDelayed(new Runnable() {

                                @Override
                                public void run() {

                                    for (DeviceInfo dev_info : DeviceList) {
                                        if (dev_info.UID.equals(mstrUid_FromCustomURL)) {

                                            Bundle extras = new Bundle();
                                            extras.putString("dev_uid", dev_info.UID);
                                            extras.putString("dev_uuid", dev_info.UUID);
                                            extras.putString("dev_nickname", dev_info.NickName);
                                            extras.putString("conn_status", dev_info.Status);
                                            extras.putString("view_acc", dev_info.View_Account);
                                            extras.putString("view_pwd", dev_info.View_Password);
                                            extras.putInt("camera_channel", dev_info.ChannelIndex);

                                            EventListActivity.log_event = 2;

                                            Intent intent = new Intent();
                                            intent.putExtras(extras);
                                            intent.setClass(MainActivity.this, LiveViewActivity.class);
                                            startActivityForResult(intent, REQUEST_CODE_CAMERA_VIEW);

                                            break;
                                        }
                                    }

                                }

                            }, 1000);

                        }

                    }
                }
            }
        }

        if (VERSION.SDK_INT < Build_VERSION_CODES_ICE_CREAM_SANDWICH) {
            BitmapDrawable bg = (BitmapDrawable) getResources().getDrawable(R.drawable.bg_striped);
            bg.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
            getSupportActionBar().setBackgroundDrawable(bg);
        }

        MyCamera.init();

        if (isNetworkAvailable()) {
            setupView();
        } else {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            setContentView(R.layout.no_network_connection);

            Button btnRetry = (Button) findViewById(R.id.btnRetry);
            btnRetry.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (isNetworkAvailable())
                        setupView();
                }
            });
        }
        //eddie GCM
//		Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
//		registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
//		registrationIntent.putExtra("sender", com.tutk.P2PCam264.DatabaseManager.s_GCM_sender);
//		startService(registrationIntent);

        Bundle bundle = this.getIntent().getExtras();
        if (bundle != null) {
            String GCMDevUID = bundle.getString("dev_uid");
            for (int i = 0; i < DeviceList.size(); i++) {
                if (DeviceList.get(i).UID.equals(GCMDevUID) == true) {
                    DeviceList.get(i).n_gcm_count++;
                    adapter.notifyDataSetChanged();
                }
            }
        }

        filter = new IntentFilter();
        filter.addAction(MainActivity.class.getName());
        resultStateReceiver = new ResultStateReceiver();

        registerReceiver(resultStateReceiver, filter);
        com.tutk.P2PCam264.DatabaseManager.n_mainActivity_Status = 1;


        //quit app push
        Intent agzaintent = getIntent();
        Bundle agzabundle = agzaintent.getExtras();
        if (agzabundle != null) {
            final Handler handler = new Handler();
            final Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    Intent intent = getIntent();
                    Bundle bundle = intent.getExtras();
                    String AgzaString = bundle.getString("Agza");
                    if (AgzaString != null) {
                        //push image or video
                        if (AgzaString.equals("AgzaMedia")) {
                            if (bundle != null) {
                                String GCMDevUID = bundle.getString("dev_uid");
                                for (int i = 0; i < DeviceList.size(); i++) {
                                    if (DeviceList.get(i).UID.equals(GCMDevUID)) {
                                        if (DeviceList.get(i).Status.equals(getText(R.string.connstus_connecting).toString())) {
                                            DeviceList.get(i).n_gcm_count = 0;
                                            Bundle extras = new Bundle();
                                            extras.putString("dev_uuid", DeviceList.get(i).UUID);
                                            extras.putString("dev_uid", DeviceList.get(i).UID);
                                            extras.putString("dev_nickname", DeviceList.get(i).NickName);
                                            extras.putInt("camera_channel", DeviceList.get(i).ChannelIndex);
                                            extras.putString("view_acc", DeviceList.get(i).View_Account);
                                            extras.putString("view_pwd", DeviceList.get(i).View_Password);
                                            Intent Mainintent = new Intent(MainActivity.this, EventListActivity.class);
                                            Intent Mainintents = new Intent(MainActivity.this, AgzaMediaActivity.class);
                                            Mainintents.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                                            Mainintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                                            Mainintents.putExtras(Mainintents);
                                            Mainintents.putExtras(extras);
                                            Mainintents.putExtras(bundle);
                                            Mainintent.putExtras(Mainintent);
                                            Mainintent.putExtras(extras);
                                            Mainintent.putExtras(bundle);
                                            if (AgzaString != null) {
                                                if (AgzaString.equals("AgzaMedia")) {
                                                    startActivity(Mainintents);
                                                } else {
                                                    startActivity(Mainintent);
                                                    Log.d("TPNS", "AgzaMedia Fail");
                                                }
                                            } else {
                                                startActivity(Mainintent);
                                            }
                                        } else {
                                            DeviceList.get(i).n_gcm_count++;
                                            adapter.notifyDataSetChanged();
                                        }
                                    }
                                }
                            }
                            setIntent(intent);
                            Log.d("TPNS", " AgzaMediaPush Start");
                        } else {
                            //push string
                            if (bundle != null) {
                                String GCMDevUID = bundle.getString("dev_uid");
                                for (int i = 0; i < DeviceList.size(); i++) {
                                    if (DeviceList.get(i).UID.equals(GCMDevUID)) {
                                        if (DeviceList.get(i).Status.equals(getText(R.string.connstus_connecting).toString())) {
                                            DeviceList.get(i).n_gcm_count = 0;
                                            Bundle extras = new Bundle();
                                            extras.putString("dev_uuid", DeviceList.get(i).UUID);
                                            extras.putString("dev_uid", DeviceList.get(i).UID);
                                            extras.putString("dev_nickname", DeviceList.get(i).NickName);
                                            extras.putInt("camera_channel", DeviceList.get(i).ChannelIndex);
                                            extras.putString("view_acc", DeviceList.get(i).View_Account);
                                            extras.putString("view_pwd", DeviceList.get(i).View_Password);
                                            Intent Mainintent = new Intent(MainActivity.this, EventListActivity.class);
                                            Mainintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                                            Mainintent.putExtras(Mainintent);
                                            Mainintent.putExtras(extras);
                                            Mainintent.putExtras(bundle);
                                            startActivity(Mainintent);
                                        } else {
                                            DeviceList.get(i).n_gcm_count++;
                                            adapter.notifyDataSetChanged();
                                        }
                                    }
                                }
                            }
                            setIntent(intent);
                            Log.d("TPNS", " AgzaStringPush Start");
                        }
                    } else {
                        Log.d("TPNS", "MainActivity Start");
                    }
                    setIntent(intent);
                }
            };
            handler.postDelayed(runnable, 500);
        } else {
            Log.d("TPNS", "MainActivity Start");
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(resultStateReceiver);
        com.tutk.P2PCam264.DatabaseManager.n_mainActivity_Status = 0;
        quit();
    }

    @Override
    protected void onStart() {
        com.tutk.P2PCam264.DatabaseManager.n_mainActivity_Status = 1;
        super.onStart();
        Log.d("TPNS", "onStart");
        // FlurryAgent.onStartSession(this, "Q1SDXDZQ21BQMVUVJ16W");
    }

//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//
//		menu.clear();
//
//		SubMenu subMenu = menu.addSubMenu("");
//
//		if (isNetworkAvailable() && CameraList.size() < CAMERA_MAX_LIMITS) {
//
//			subMenu.add(Menu.NONE, OPT_MENU_ITEM_ADD_CAM, 1, getText(R.string.optAddCamera).toString());
//			subMenu.add(Menu.NONE, OPT_MENU_ITEM_ABOUT, 2, getText(R.string.optAbout).toString());
//			subMenu.add(Menu.NONE, OPT_MENU_ITEM_EXIT, 3, getText(R.string.optExit).toString());
//
//		} else {
//
//			subMenu.add(Menu.NONE, OPT_MENU_ITEM_ABOUT, 2, getText(R.string.optAbout).toString());
//			subMenu.add(Menu.NONE, OPT_MENU_ITEM_EXIT, 3, getText(R.string.optExit).toString());
//		}
//
//		MenuItem subMenu1Item = subMenu.getItem();
//		subMenu1Item.setIcon(R.drawable.ic_menu_overflow);
//		subMenu1Item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
//
//		if (VERSION.SDK_INT > 10 && ViewConfiguration.get(getApplicationContext()).hasPermanentMenuKey() || VERSION.SDK_INT < 11) {
//
//			if (isNetworkAvailable() && CameraList.size() < CAMERA_MAX_LIMITS) {
//
//				menu.add(Menu.NONE, OPT_MENU_ITEM_ADD_CAM, 1, getText(R.string.optAddCamera).toString());
//				menu.add(Menu.NONE, OPT_MENU_ITEM_ABOUT, 2, getText(R.string.optAbout).toString());
//				menu.add(Menu.NONE, OPT_MENU_ITEM_EXIT, 3, getText(R.string.optExit).toString());
//
//			} else {
//
//				menu.add(Menu.NONE, OPT_MENU_ITEM_ABOUT, 2, getText(R.string.optAbout).toString());
//				menu.add(Menu.NONE, OPT_MENU_ITEM_EXIT, 3, getText(R.string.optExit).toString());
//			}
//		}
//
//		return super.onCreateOptionsMenu(menu);
//	}

//	@Override
//	public boolean onOptionsItemSelected(MenuItem item) {
//
//		int id = item.getItemId();
//
//		switch (id) {
//		case OPT_MENU_ITEM_ADD_CAM:
//
//			if (CameraList.size() < CAMERA_MAX_LIMITS) {
//				Intent intent = new Intent();
//				intent.setClass(MainActivity.this, AddDeviceActivity.class);
//				startActivityForResult(intent, REQUEST_CODE_CAMERA_ADD);
//			}
//			break;
//
//		case OPT_MENU_ITEM_ABOUT:
//
//			String versionName = "";
//			try {
//				versionName = this.getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
//			} catch (NameNotFoundException e) {
//			}
//
//			AboutDialog dlg = new AboutDialog(MainActivity.this, getText(R.string.dialog_AboutMe).toString(), versionName);
//			dlg.setCanceledOnTouchOutside(true);
//			dlg.show();
//			break;
//
//		case OPT_MENU_ITEM_EXIT:
//			quit();
//
//		default:
//			break;
//		}
//
//		return super.onOptionsItemSelected(item);
//	}

	/*@Override public boolean onContextItemSelected(final android.view.MenuItem item) { Bundle
     * extras = new Bundle(); Intent intent = new Intent(); switch (item.getItemId()) { case
	 * CTX_MENU_ITEM_RECONNECT: selectedCamera.disconnect();
	 * selectedCamera.connect(selectedDevice.UID); selectedCamera.start(Camera.DEFAULT_AV_CHANNEL,
	 * selectedDevice.View_Account, selectedDevice.View_Password);
	 * selectedCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
	 * AVIOCTRLDEFs.IOTYPE_USER_IPCAM_DEVINFO_REQ,
	 * AVIOCTRLDEFs.SMsgAVIoctrlDeviceInfoReq.parseContent());
	 * selectedCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
	 * AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETSUPPORTSTREAM_REQ,
	 * AVIOCTRLDEFs.SMsgAVIoctrlGetSupportStreamReq.parseContent()); break; case
	 * CTX_MENU_ITEM_EDIT_CAM: extras.putLong("db_id", selectedDevice.DBID);
	 * extras.putString("dev_uuid", selectedDevice.UUID); extras.putString("dev_uid",
	 * selectedDevice.UID); extras.putString("view_acc", selectedDevice.View_Account);
	 * extras.putString("view_pwd", selectedDevice.View_Password); extras.putString("dev_nickname",
	 * selectedDevice.NickName); extras.putInt("camera_channel", selectedDevice.ChannelIndex);
	 * intent.putExtras(extras); intent.setClass(MainActivity.this, EditDeviceActivity.class);
	 * startActivityForResult(intent, REQUEST_CODE_CAMERA_EDIT); break; case
	 * CTX_MENU_ITEM_VIEW_EVENT: extras.putString("dev_uuid", selectedDevice.UUID);
	 * extras.putString("dev_uid", selectedDevice.UID); extras.putString("dev_nickname",
	 * selectedDevice.NickName); extras.putString("view_acc", selectedDevice.View_Account);
	 * extras.putString("view_pwd", selectedDevice.View_Password); extras.putInt("camera_channel",
	 * selectedDevice.ChannelIndex); intent.putExtras(extras); intent.setClass(MainActivity.this,
	 * EventListActivity.class); startActivity(intent); break; case CTX_MENU_ITEM_VIEW_SNAPSHOT: //
	 * intent.setClass(MainActivity.this, PhotoThumbnailsActivity.class); //
	 * intent.putExtra("dev_uid", selectedDevice.UID); // startActivity(intent); File folder = new
	 * File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Snapshot/" +
	 * selectedDevice.UID); allFiles = folder.list(); if (allFiles != null && allFiles.length > 0) {
	 * SCAN_PATH = Environment.getExternalStorageDirectory().toString() + "/Snapshot/" +
	 * selectedDevice.UID + "/" + allFiles[allFiles.length - 1]; } else { SCAN_PATH =
	 * Environment.getExternalStorageDirectory().toString() + "/Snapshot/" + selectedDevice.UID; }
	 * if (allFiles == null || allFiles.length == 0) { String msg =
	 * MainActivity.this.getText(R.string.tips_no_snapshot_found).toString();
	 * Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show(); } else { if (conn != null)
	 * { conn.disconnect(); } conn = new MediaScannerConnection(this, this); conn.connect(); }
	 * break; case CTX_MENU_ITEM_REMOVE_CAM: new
	 * AlertDialog.Builder(MainActivity.this).setIcon(android
	 * .R.drawable.ic_dialog_alert).setTitle(getText
	 * (R.string.tips_warning)).setMessage(getText(R.string
	 * .tips_remove_camera_confirm)).setPositiveButton(getText(R.string.ok), new
	 * DialogInterface.OnClickListener() {
	 * @Override public void onClick(DialogInterface dialog, int which) { // stop & remove camera
	 * selectedCamera.stop(MyCamera.DEFAULT_AV_CHANNEL); selectedCamera.disconnect();
	 * selectedCamera.unregisterIOTCListener(MainActivity.this); CameraList.remove(selectedCamera);
	 * // remove snapshot from database & storage DatabaseManager manager = new
	 * DatabaseManager(MainActivity.this); //SQLiteDatabase db = manager.getReadableDatabase();
	 * //Cursor cursor = db.query(DatabaseManager.TABLE_SNAPSHOT, new String[] { "_id", "dev_uid",
	 * "file_path", "time" }, "dev_uid = '" + selectedDevice.UID + "'", null, null, null,
	 * "_id LIMIT " + MainActivity.CAMERA_MAX_LIMITS); //while (cursor.moveToNext()) { // String
	 * file_path = cursor.getString(2); // File file = new File(file_path); // if (file.exists()) //
	 * file.delete(); //} //cursor.close(); //db.close();
	 * //manager.removeSnapshotByUID(selectedDevice.UID); File folder = new
	 * File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Snapshot/" +
	 * selectedDevice.UID); allFiles = folder.list(); if (allFiles != null && allFiles.length > 0) {
	 * File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
	 * "/Snapshot/" + selectedDevice.UID); if (file.exists()) file.delete(); } // remove camera from
	 * database manager.removeDeviceByUID(selectedDevice.UID); // remove item from listview
	 * DeviceList.remove(selectedDevice); adapter.notifyDataSetChanged(); String notify = ""; if
	 * (CameraList.size() == 0) notify = String.format(getText(R.string.ntfAppRunning).toString(),
	 * getText(R.string.app_name).toString()); else notify =
	 * String.format(getText(R.string.ntfCameraRunning).toString(), CameraList.size());
	 * verifyCameraLimit(); startOnGoingNotification(notify); }
	 * }).setNegativeButton(getText(R.string.cancel), new DialogInterface.OnClickListener() {
	 * @Override public void onClick(DialogInterface dialog, int which) { } }).show(); break; }
	 * return super.onContextItemSelected(item); } */

    @Override
    protected void onStop() {
        com.tutk.P2PCam264.DatabaseManager.n_mainActivity_Status = 0;
        super.onStop();
        Log.d("TPNS", "onStop");
        // FlurryAgent.onEndSession(this);
    }

    @Override
    protected void onResume() {
        super.onResume();

        Log.d("TPNS", "onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("TPNS", "onPause");
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        quit();
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//
////            Builder builder = new Builder(MainActivity.this);
////            builder.setMessage(MainActivity.this.getText(R.string.dialog_Exit));
////
////            builder.setPositiveButton(MainActivity.this.getText(R.string.btnExit), new OnClickListener() {
////                @Override
////                public void onClick(DialogInterface dialog, int which) {
////                    dialog.dismiss();
////                    quit();
////
////                }
////            });
////            builder.setNeutralButton(MainActivity.this.getText(R.string.btnRunInBackground), new OnClickListener() {
////                @Override
////                public void onClick(DialogInterface dialog, int which) {
////                    dialog.dismiss();
////                    MainActivity.this.runOnUiThread(new Runnable() {
////                        @Override
////                        public void run() {
////                            moveTaskToBack(true);
////                        }
////                    });
////                    if (CameraList.size() > 0) {
////                        MainActivity.this.moveTaskToBack(true);
////                    }
////                }
////            });
////            builder.setNegativeButton(MainActivity.this.getText(R.string.btnCancel), new OnClickListener() {
////                @Override
////                public void onClick(DialogInterface dialog, int which) {
////                    dialog.dismiss();
////                }
////            });
////            builder.create().show();
//            return false;
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        Configuration cfg = getResources().getConfiguration();

        if (cfg.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            System.out.println("ORIENTATION_LANDSCAPE");

        } else if (cfg.orientation == Configuration.ORIENTATION_PORTRAIT) {
            System.out.println("ORIENTATION_PORTRAIT");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_CAMERA_ADD) {

            switch (resultCode) {
                case RESULT_OK:

                    Bundle extras = data.getExtras();
                    long db_id = extras.getLong("db_id");
                    String dev_nickname = extras.getString("dev_nickname");
                    String dev_uid = extras.getString("dev_uid");
                    String view_acc = extras.getString("view_acc");
                    String view_pwd = extras.getString("view_pwd");
                    int event_notification = 3;
                    int channel = extras.getInt("camera_channel");

                    boolean flg = extras.getBoolean("flg");
                    if (flg) {
                        // show to user
                        Builder builder = new Builder(this);
                        builder.setTitle(getText(R.string.tip));
                        builder.setMessage(getText(R.string.setup_uid_to_device) + "\n" + dev_uid);
                        builder.setPositiveButton(getText(R.string.ok), new OnClickListener() {

                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                arg0.dismiss();
                            }
                        });
                        builder.create().show();
                    }

                    MyCamera camera = new MyCamera(dev_nickname, dev_uid, view_acc, view_pwd);
                    DeviceInfo dev = new DeviceInfo(db_id, camera.getUUID(), dev_nickname, dev_uid, view_acc, view_pwd, "", event_notification, channel,
                            null);
                    DeviceList.add(dev);

                    camera.registerIOTCListener(this);
                    camera.connect(dev_uid);
                    camera.start(MyCamera.DEFAULT_AV_CHANNEL, view_acc, view_pwd);
                    camera.sendIOCtrl(MyCamera.DEFAULT_AV_CHANNEL, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_DEVINFO_REQ,
                            AVIOCTRLDEFs.SMsgAVIoctrlDeviceInfoReq.parseContent());
                    camera.sendIOCtrl(MyCamera.DEFAULT_AV_CHANNEL, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETSUPPORTSTREAM_REQ,
                            AVIOCTRLDEFs.SMsgAVIoctrlGetSupportStreamReq.parseContent());
                    camera.sendIOCtrl(MyCamera.DEFAULT_AV_CHANNEL, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ,
                            AVIOCTRLDEFs.SMsgAVIoctrlGetAudioOutFormatReq.parseContent());
                    camera.sendIOCtrl(MyCamera.DEFAULT_AV_CHANNEL, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GET_TIMEZONE_REQ,
                            AVIOCTRLDEFs.SMsgAVIoctrlTimeZone.parseContent());

                    camera.LastAudioMode = 1;

                    CameraList.add(camera);

                    adapter.notifyDataSetChanged();


                    String notify = "";

                    if (CameraList.size() == 0)
                        notify = String.format(getText(R.string.ntfAppRunning).toString(), getText(R.string.app_name).toString());
                    else
                        notify = String.format(getText(R.string.ntfCameraRunning).toString(), CameraList.size());

                    verifyCameraLimit();
                    startOnGoingNotification(notify);

                    break;
            }
        } else if (requestCode == REQUEST_CODE_CAMERA_VIEW) {

            if (mCustomURL_CmdID != -1) {
                finish();
                return;
            }

            switch (resultCode) {
                case RESULT_OK:

                    Bundle extras = data.getExtras();
                    String dev_uuid = extras.getString("dev_uuid");
                    String dev_uid = extras.getString("dev_uid");
                    byte[] byts = extras.getByteArray("snapshot");
                    int channelIndex = extras.getInt("camera_channel");

                    Bitmap snapshot = null;
                    if (byts != null && byts.length > 0)
                        snapshot = DatabaseManager.getBitmapFromByteArray(byts);

                    for (int i = 0; i < DeviceList.size(); i++) {

                        if (dev_uuid.equalsIgnoreCase(DeviceList.get(i).UUID) && dev_uid.equalsIgnoreCase(DeviceList.get(i).UID)) {

                            DeviceList.get(i).ChannelIndex = channelIndex;

                            if (snapshot != null)
                                DeviceList.get(i).Snapshot = snapshot;

                            adapter.notifyDataSetChanged();

                            break;
                        }
                    }

                    break;
            }
        } else if (requestCode == REQUEST_CODE_CAMERA_EDIT) {

            switch (resultCode) {
                case RESULT_OK:

                    adapter.notifyDataSetChanged();
            }
        } else if (requestCode == REQUEST_CODE_CAMERA_HISTORY) {

        }
    }

    @SuppressWarnings("deprecation")
    @Override
    protected Dialog onCreateDialog(int id) {
        if (id == CONTEXT_MENU_ID) {
            return iconContextMenu.createMenu("");
        }
        return super.onCreateDialog(id);
    }

    private void quit() {

//		stopOnGoingNotification();



        for (MyCamera camera : CameraList) {
            // camera.stop(MyCamera.DEFAULT_AV_CHANNEL);
            camera.disconnect();
            camera.unregisterIOTCListener(this);
        }
//        Intent intent=new Intent(MainActivity.this, BoxListActivity.class);
//        startActivity(intent);
//        overridePendingTransition(R.anim.fade_in,R.anim.fade_out);
        finish();// IOTC
//		System.out.println("kill process");

//		MyCamera.uninit();

//		int pid = android.os.Process.myPid();
//		Log.d("TPNS","pid " + pid);
//		android.os.Process.killProcess(pid);


    }

    private void setupView() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.main);

        // imgAddDevice = (ImageView) findViewById(R.id.imgAddDevice);
        // imgAddDevice.setOnClickListener(imgAddDeviceOnClickListener);

        listView = (ListView) findViewById(R.id.lstCameraList);
        addDeviceView = getLayoutInflater().inflate(R.layout.add_device_row, null);
        adapter = new DeviceListAdapter(this);

        boolean bFirstTime = true;
        if (CameraList.size() > 0) {
            // CameraList.clear();
            bFirstTime = false;
        }
        initCameraList(bFirstTime);
        listView.addFooterView(addDeviceView);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(listViewOnItemClickListener);
        listView.setOnItemLongClickListener(listViewOnItemLongClickListener);
        // this.registerForContextMenu(listView);

        // fix remove footview of listadapter
        verifyCameraLimit();
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();

        // return activeNetworkInfo != null;
        return true;
    }

    private void initCameraList(boolean bFirstTime) {

        if (bFirstTime) {
            DatabaseManager manager = new DatabaseManager(this);
            SQLiteDatabase db = manager.getReadableDatabase();
            Cursor cursor = db.query(DatabaseManager.TABLE_DEVICE, new String[]{"_id", "dev_nickname", "dev_uid", "dev_name", "dev_pwd",
                            "view_acc", "view_pwd", "event_notification", "camera_channel", "snapshot", "ask_format_sdcard"}, null, null, null, null,
                    "_id LIMIT " + MainActivity.CAMERA_MAX_LIMITS);

            while (cursor.moveToNext()) {

                long db_id = cursor.getLong(0);
                String dev_nickname = cursor.getString(1);
                String dev_uid = cursor.getString(2);
                String view_acc = cursor.getString(5);
                String view_pwd = cursor.getString(6);
                int event_notification = cursor.getInt(7);
                int channel = cursor.getInt(8);
                byte[] bytsSnapshot = cursor.getBlob(9);
                int ask_format_sdcard = cursor.getInt(10);
                Bitmap snapshot = (bytsSnapshot != null && bytsSnapshot.length > 0) ? DatabaseManager.getBitmapFromByteArray(bytsSnapshot) : null;

                MyCamera camera = new MyCamera(dev_nickname, dev_uid, view_acc, view_pwd);
                DeviceInfo dev = new DeviceInfo(db_id, camera.getUUID(), dev_nickname, dev_uid, view_acc, view_pwd, "", event_notification, channel,
                        snapshot);
                dev.ShowTipsForFormatSDCard = ask_format_sdcard == 1;
                DeviceList.add(dev);

                camera.registerIOTCListener(this);
                camera.connect(dev_uid);
                camera.start(Camera.DEFAULT_AV_CHANNEL, view_acc, view_pwd);
                camera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETSUPPORTSTREAM_REQ,
                        SMsgAVIoctrlGetSupportStreamReq.parseContent());
                camera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_DEVINFO_REQ,
                        AVIOCTRLDEFs.SMsgAVIoctrlDeviceInfoReq.parseContent());
                camera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ,
                        AVIOCTRLDEFs.SMsgAVIoctrlGetAudioOutFormatReq.parseContent());
                camera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GET_TIMEZONE_REQ,
                        AVIOCTRLDEFs.SMsgAVIoctrlTimeZone.parseContent());

                camera.LastAudioMode = 1;

                CameraList.add(camera);
            }

            cursor.close();
            db.close();
        }
        String notify = "";

        if (CameraList.size() == 0)
            notify = String.format(getText(R.string.ntfAppRunning).toString(), getText(R.string.app_name).toString());
        else
            notify = String.format(getText(R.string.ntfCameraRunning).toString(), CameraList.size());

        startOnGoingNotification(notify);
    }

    private void initContextMenu() {
        Resources res = getResources();
//
//		// init the menu
        if (iconContextMenu == null)
            iconContextMenu = new IconContextMenu(this, CONTEXT_MENU_ID);
//
        iconContextMenu.clearItems();
//
        iconContextMenu.addItem(res, getText(R.string.ctxReconnect), R.drawable.ic_reconnect_camera, CTX_MENU_ITEM_RECONNECT);
        iconContextMenu.addItem(res, getText(R.string.ctxEditCamera), R.drawable.ic_edit_camera, CTX_MENU_ITEM_EDIT_CAM);
        if (selectedCamera.getEventListSupported(0))
            iconContextMenu.addItem(res, getText(R.string.ctxViewEvent), R.drawable.ic_view_event, CTX_MENU_ITEM_VIEW_EVENT);
        iconContextMenu.addItem(res, getText(R.string.ctxViewSnapshot), R.drawable.ic_album, CTX_MENU_ITEM_VIEW_SNAPSHOT);
        iconContextMenu.addItem(res, getText(R.string.ctxRemoveCamera), R.drawable.ic_delete_camera, CTX_MENU_ITEM_REMOVE_CAM);

//		// set onClick listener for context menu
        iconContextMenu.setOnClickListener(new IconContextMenu.IconContextMenuOnClickListener() {
            @Override
            public void onClick(int menuId) {

                Bundle extras = new Bundle();
                Intent intent = new Intent();

                switch (menuId) {
                    case CTX_MENU_ITEM_RECONNECT:

                        if (m_threadReconnect != null) {
                            m_threadReconnect.stopCheck = true;
                            m_threadReconnect.interrupt();
                            m_threadReconnect = null;
                        }
                        selectedCamera.disconnect();
                        selectedCamera.connect(selectedDevice.UID);
                        selectedCamera.start(Camera.DEFAULT_AV_CHANNEL, selectedDevice.View_Account, selectedDevice.View_Password);
                        selectedCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_DEVINFO_REQ,
                                AVIOCTRLDEFs.SMsgAVIoctrlDeviceInfoReq.parseContent());
                        selectedCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETSUPPORTSTREAM_REQ,
                                AVIOCTRLDEFs.SMsgAVIoctrlGetSupportStreamReq.parseContent());
                        selectedCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ,
                                AVIOCTRLDEFs.SMsgAVIoctrlGetAudioOutFormatReq.parseContent());
                        selectedCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GET_TIMEZONE_REQ,
                                AVIOCTRLDEFs.SMsgAVIoctrlTimeZone.parseContent());

                        break;

                    case CTX_MENU_ITEM_EDIT_CAM:

                        extras.putLong("db_id", selectedDevice.DBID);
                        extras.putString("dev_uuid", selectedDevice.UUID);
                        extras.putString("dev_uid", selectedDevice.UID);
                        extras.putString("view_acc", selectedDevice.View_Account);
                        extras.putString("view_pwd", selectedDevice.View_Password);
                        extras.putString("dev_nickname", selectedDevice.NickName);
                        extras.putInt("camera_channel", selectedDevice.ChannelIndex);

                        intent.putExtras(extras);
                        intent.setClass(MainActivity.this, EditDeviceActivity.class);
                        startActivityForResult(intent, REQUEST_CODE_CAMERA_EDIT);

                        break;

                    case CTX_MENU_ITEM_VIEW_EVENT:

                        selectedDevice.n_gcm_count = 0;
                        extras.putString("dev_uuid", selectedDevice.UUID);
                        extras.putString("dev_uid", selectedDevice.UID);
                        extras.putString("dev_nickname", selectedDevice.NickName);
                        extras.putString("view_acc", selectedDevice.View_Account);
                        extras.putString("view_pwd", selectedDevice.View_Password);
                        extras.putInt("camera_channel", selectedDevice.ChannelIndex);

                        intent.putExtras(extras);
                        intent.setClass(MainActivity.this, EventListActivity.class);
                        startActivity(intent);

                        break;

                    case CTX_MENU_ITEM_VIEW_SNAPSHOT:

                        // intent.setClass(MainActivity.this, PhotoThumbnailsActivity.class);
                        // intent.putExtra("dev_uid", selectedDevice.UID);
                        // startActivity(intent);

                        File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Snapshot/" + selectedDevice.UID);
                        // File folder = new
                        // File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath()
                        // + "/Snapshot");
                        String[] allFiles = folder.list();
                        if (allFiles != null && allFiles.length > 0) {

                            String file = folder.getAbsolutePath() + "/" + allFiles[allFiles.length - 1];

						/*MediaScannerConnection.scanFile(MainActivity.this, new String[] {
                         * file.toString() }, new String[] {"image/*"}, new
						 * MediaScannerConnection.OnScanCompletedListener() { public void
						 * onScanCompleted(String path, Uri uri) { Glog.I("ExternalStorage",
						 * "Scanned " + path + ":"); Glog.I("ExternalStorage", "-> uri=" + uri);
						 * Intent intent = new Intent(Intent.ACTION_VIEW); //
						 * intent.addCategory(Intent.CATEGORY_OPENABLE); //
						 * intent.setType("image/*"); intent.setDataAndType(uri, "image/*");
						 * startActivity(intent); } }); /* intent.setAction(Intent.ACTION_VIEW); Uri
						 * hacked_uri = Uri.parse("file://" + Uri.parse(file).getPath());
						 * intent.setDataAndType(hacked_uri, "image/*"); startActivity(intent); */

                            Intent intent2 = new Intent(MainActivity.this, GridViewGalleryActivity.class);
                            intent2.putExtra("snap", selectedDevice.UID);
                            intent2.putExtra("images_path", folder.getAbsolutePath());
                            startActivity(intent2);

                        } else {
                            String msg = MainActivity.this.getText(R.string.tips_no_snapshot_found).toString();
                            Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                        }

                        break;

                    case CTX_MENU_ITEM_REMOVE_CAM:

                        new Builder(MainActivity.this).setIcon(android.R.drawable.ic_dialog_alert).setTitle(getText(R.string.tips_warning))
                                .setMessage(getText(R.string.tips_remove_camera_confirm))
                                .setPositiveButton(getText(R.string.ok), new OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                        //Agza unmapping
                                        String udid = DatabaseManager.uid_Produce(MainActivity.this);
                                        AgzaPushUtil.unmappingPush(MainActivity.this, selectedDevice.UID, "com.tutk.P2PCamLive", udid);
                                        Log.d("TPNS", "unmapping" + selectedDevice.UID);

                                        //GCM
                                        thread = new ThreadTPNS(MainActivity.this, selectedDevice.UID);
                                        thread.start();
                                        Log.d("TPNS", "GCM: unmapping" + selectedDevice.UID);

//							TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
//							HttpGetTool HttpGetTool=new HttpGetTool(MainActivity.this,MainActivity.class.getName());
//						    HttpGetTool.execute(com.tutk.P2PCam264.DatabaseManager.s_GCM_PHP_URL+"?cmd=unreg_mapping&token="+com.tutk.P2PCam264.DatabaseManager.s_GCM_token+"&appid="+com.tutk.P2PCam264.DatabaseManager.s_Package_name+"&uid="+selectedDevice.UID+"&imei="+tm.getDeviceId());
                                        // stop & remove camera
                                        selectedCamera.stop(Camera.DEFAULT_AV_CHANNEL);
                                        selectedCamera.disconnect();
                                        selectedCamera.unregisterIOTCListener(MainActivity.this);
                                        CameraList.remove(selectedCamera);
                                        // remove snapshot from database & storage
                                        DatabaseManager manager = new DatabaseManager(MainActivity.this);
                                        SQLiteDatabase db = manager.getReadableDatabase();
                                        Cursor cursor = db
                                                .query(DatabaseManager.TABLE_SNAPSHOT, new String[]{"_id", "dev_uid", "file_path", "time"},
                                                        "dev_uid = '" + selectedDevice.UID + "'", null, null, null, "_id LIMIT "
                                                                + MainActivity.CAMERA_MAX_LIMITS);

                                        while (cursor.moveToNext()) {
                                            String file_path = cursor.getString(2);
                                            File file = new File(file_path);
                                            if (file.exists())
                                                file.delete();
                                        }
                                        cursor.close();
                                        db.close();

                                        manager.removeSnapshotByUID(selectedDevice.UID);

                                        // remove camera from database
                                        manager.removeDeviceByUID(selectedDevice.UID);

                                        // remove item from listview
                                        DeviceList.remove(selectedDevice);
                                        adapter.notifyDataSetChanged();

                                        String notify = "";

                                        if (CameraList.size() == 0)
                                            notify = String.format(getText(R.string.ntfAppRunning).toString(), getText(R.string.app_name).toString());
                                        else
                                            notify = String.format(getText(R.string.ntfCameraRunning).toString(), CameraList.size());

                                        verifyCameraLimit();
                                        startOnGoingNotification(notify);
                                        MainActivity.showAlert(MainActivity.this, getText(R.string.tips_warning),
                                                getText(R.string.tips_remove_camera_ok), getText(R.string.ok));
                                    }
                                }).setNegativeButton(getText(R.string.cancel), new OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).show();

                        break;
                }
            }
        });
    }

    private void verifyCameraLimit() {

        if (CameraList.size() < CAMERA_MAX_LIMITS) {

            if (listView.getFooterViewsCount() == 0) {
                listView.addFooterView(addDeviceView);
                adapter.notifyDataSetChanged();
            }

        } else {

            if (listView.getFooterViewsCount() > 0) {
                listView.removeFooterView(addDeviceView);
                adapter.notifyDataSetChanged();
            }
        }

        this.invalidateOptionsMenu();
    }

    @SuppressWarnings("deprecation")
    private void startOnGoingNotification(String Text) {

        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        try {

            Intent intent = new Intent(this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            Notification notification = new Notification(R.drawable.nty_app, String.format(getText(R.string.ntfAppRunning).toString(),
                    getText(R.string.app_name).toString()), 0);
            notification.setLatestEventInfo(this, getText(R.string.app_name), Text, pendingIntent);
            notification.flags |= Notification.FLAG_ONGOING_EVENT;

            //manager.notify(0, notification);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void stopOnGoingNotification() {

        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.cancel(0);
        manager.cancel(1);
    }

    @SuppressWarnings("deprecation")
    //GCM TPNS//
    private void showNotification(DeviceInfo dev, int camChannel, int evtType, long evtTime) {


        try {


            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

            Bundle extras = new Bundle();
            extras.putString("dev_uuid", dev.UUID);
            extras.putString("dev_uid", dev.UID);
            extras.putString("dev_nickname", dev.NickName);
            extras.putInt("camera_channel", camChannel);
            extras.putString("view_acc", dev.View_Account);
            extras.putString("view_pwd", dev.View_Password);

            Intent intent = new Intent(this, EventListActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtras(extras);

            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            Calendar cal = Calendar.getInstance();
            cal.setTimeZone(TimeZone.getDefault());
            cal.setTimeInMillis(evtTime);
            cal.add(Calendar.MONTH, 0);

            //eddie 104/12/4
//			Notification notification = new Notification(R.drawable.nty_alert, String.format(getText(R.string.ntfIncomingEvent).toString(),
//					dev.NickName), cal.getTimeInMillis());
//			notification.flags |= Notification.FLAG_AUTO_CANCEL;
//			notification.flags |= Notification.FLAG_NO_CLEAR;
//
//			if (dev.EventNotification == 0)
//				notification.defaults = Notification.DEFAULT_LIGHTS;
//			else if (dev.EventNotification == 1)
//				notification.defaults = Notification.DEFAULT_SOUND;
//			else if (dev.EventNotification == 2)
//				notification.defaults = Notification.DEFAULT_VIBRATE;
//			else
//				notification.defaults = Notification.DEFAULT_ALL;
//
//			notification.setLatestEventInfo(this, String.format(getText(R.string.ntfIncomingEvent).toString(), dev.NickName),
//					String.format(getText(R.string.ntfLastEventIs).toString(), getEventType(this, evtType, false)), pendingIntent);
//
//			manager.notify(1, notification);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showSDCardFormatDialog(final Camera camera, final DeviceInfo device) {

        final AlertDialog dlg = new Builder(MainActivity.this).create();
        dlg.setTitle(R.string.dialog_FormatSDCard);
        dlg.setIcon(android.R.drawable.ic_menu_more);

        LayoutInflater inflater = dlg.getLayoutInflater();
        View view = inflater.inflate(R.layout.format_sdcard, null);
        dlg.setView(view);

        final CheckBox chbShowTipsFormatSDCard = (CheckBox) view.findViewById(R.id.chbShowTipsFormatSDCard);
        final Button btnFormat = (Button) view.findViewById(R.id.btnFormatSDCard);
        final Button btnClose = (Button) view.findViewById(R.id.btnClose);

        btnFormat.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                camera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_FORMATEXTSTORAGE_REQ,
                        AVIOCTRLDEFs.SMsgAVIoctrlFormatExtStorageReq.parseContent(0));
                device.ShowTipsForFormatSDCard = chbShowTipsFormatSDCard.isChecked();

                DatabaseManager db = new DatabaseManager(MainActivity.this);
                db.updateDeviceAskFormatSDCardByUID(device.UID, device.ShowTipsForFormatSDCard);

                dlg.dismiss();
            }
        });

        btnClose.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                device.ShowTipsForFormatSDCard = chbShowTipsFormatSDCard.isChecked();

                DatabaseManager db = new DatabaseManager(MainActivity.this);
                db.updateDeviceAskFormatSDCardByUID(device.UID, device.ShowTipsForFormatSDCard);

                dlg.dismiss();
            }
        });
    }

    @Override
    public void receiveFrameData(final Camera camera, int sessionChannel, Bitmap bmp) {

    }

    @Override
    public void receiveFrameInfo(final Camera camera, int sessionChannel, long bitRate, int frameRate, int onlineNm, int frameCount,
                                 int incompleteFrameCount) {

    }

    @Override
    public void receiveSessionInfo(final Camera camera, int resultCode) {

        Bundle bundle = new Bundle();
        bundle.putString("requestDevice", ((MyCamera) camera).getUUID());

        Message msg = handler.obtainMessage();
        msg.what = resultCode;
        msg.setData(bundle);
        handler.sendMessage(msg);
    }

    @Override
    public void receiveChannelInfo(final Camera camera, int sessionChannel, int resultCode) {

        Bundle bundle = new Bundle();
        bundle.putString("requestDevice", ((MyCamera) camera).getUUID());
        bundle.putInt("sessionChannel", sessionChannel);

        Message msg = handler.obtainMessage();
        msg.what = resultCode;
        msg.setData(bundle);
        handler.sendMessage(msg);
    }

    @Override
    public void receiveIOCtrlData(final Camera camera, int sessionChannel, int avIOCtrlMsgType, byte[] data) {

        Bundle bundle = new Bundle();
        bundle.putString("requestDevice", ((MyCamera) camera).getUUID());
        bundle.putInt("sessionChannel", sessionChannel);
        bundle.putByteArray("data", data);

        Message msg = handler.obtainMessage();
        msg.what = avIOCtrlMsgType;
        msg.setData(bundle);
        handler.sendMessage(msg);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        Log.d("EVENT", "MAININTENT");
        super.onNewIntent(intent);
        // getIntent() should always return the most recent
        Bundle bundle = intent.getExtras();
        String AgzaString = bundle.getString("Agza");
        String EventType = bundle.getString("event_type");
        if (bundle != null) {
            String GCMDevUID = bundle.getString("dev_uid");
            for (int i = 0; i < DeviceList.size(); i++) {
                if (DeviceList.get(i).UID.equals(GCMDevUID)) {

                    if (DeviceList.get(i).Status.equals(getText(R.string.connstus_connected).toString())) {
                        DeviceList.get(i).n_gcm_count = 0;
                        Bundle extras = new Bundle();
                        extras.putString("dev_uuid", DeviceList.get(i).UUID);
                        extras.putString("dev_uid", DeviceList.get(i).UID);
                        extras.putString("dev_nickname", DeviceList.get(i).NickName);
                        extras.putInt("camera_channel", DeviceList.get(i).ChannelIndex);
                        extras.putString("view_acc", DeviceList.get(i).View_Account);
                        extras.putString("view_pwd", DeviceList.get(i).View_Password);
                        Intent Mainintent = new Intent(this, EventListActivity.class);
                        Intent Mainintents = new Intent(this, AgzaMediaActivity.class);
                        Mainintents.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                        Mainintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                        Mainintents.putExtras(Mainintents);
                        Mainintents.putExtras(extras);
                        Mainintents.putExtras(bundle);
                        Mainintent.putExtras(Mainintent);
                        Mainintent.putExtras(extras);
                        Mainintent.putExtras(bundle);
                        if (AgzaString != null) {
                            if (AgzaString.equals("AgzaMedia")) {
                                startActivity(Mainintents);
                            } else {
                                startActivity(Mainintent);
                            }
                        } else {
                            startActivity(Mainintent);
                            Log.d("TPNS", "AgzaMedia null");
                        }
                    } else {
                        DeviceList.get(i).n_gcm_count++;
                        adapter.notifyDataSetChanged();
                    }
                }

            }
        }
        setIntent(intent);
    }

    private void reconnect(final Camera camera, final DeviceInfo dev) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                int nCount = 0;
                while (true) {
                    try {

                        Thread.sleep(1000);
                        nCount++;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (nCount == 30) {
                        camera.disconnect();
                        camera.connect(dev.UID);
                        camera.start(Camera.DEFAULT_AV_CHANNEL, dev.View_Account, dev.View_Password);
                        camera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_DEVINFO_REQ,
                                AVIOCTRLDEFs.SMsgAVIoctrlDeviceInfoReq.parseContent());
                        camera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETSUPPORTSTREAM_REQ,
                                AVIOCTRLDEFs.SMsgAVIoctrlGetSupportStreamReq.parseContent());
                        camera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ,
                                AVIOCTRLDEFs.SMsgAVIoctrlGetAudioOutFormatReq.parseContent());
                        camera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GET_TIMEZONE_REQ,
                                AVIOCTRLDEFs.SMsgAVIoctrlTimeZone.parseContent());

                        nCount = 0;
                        break;
                    }
                }
            }
        }).start();

    }

    @Override
    public void receiveFrameDataForMediaCodec(Camera camera, int avChannel, byte[] buf, int length, int pFrmNo, byte[] pFrmInfoBuf, boolean isIframe,
                                              int codecId) {
        // TODO Auto-generated method stub

    }

    private class DeviceListAdapter extends BaseAdapter {

        private LayoutInflater mInflater;

        public DeviceListAdapter(Context context) {

            this.mInflater = LayoutInflater.from(context);
        }

        public int getCount() {

            return DeviceList.size();
        }

        public Object getItem(int position) {

            return DeviceList.get(position);
        }

        public long getItemId(int position) {

            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {

            final DeviceInfo dev = DeviceList.get(position);
            final MyCamera cam = CameraList.get(position);

            if (dev == null || cam == null)
                return null;

            ViewHolder holder = null;

            if (convertView == null) {

                convertView = mInflater.inflate(R.layout.device_list, null);

                holder = new ViewHolder();
                holder.img = (ImageView) convertView.findViewById(R.id.img);
                holder.title = (TextView) convertView.findViewById(R.id.title);
                holder.info = (TextView) convertView.findViewById(R.id.info);
                holder.status = (TextView) convertView.findViewById(R.id.status);
                holder.eventLayout = (FrameLayout) convertView.findViewById(R.id.eventLayout);
                holder.GCM_Prompt = (TextView) convertView.findViewById(R.id.GCM_Prompt);
                convertView.setTag(holder);

            } else {

                holder = (ViewHolder) convertView.getTag();
            }

            if (holder != null) {

                holder.img.setImageBitmap(dev.Snapshot);
                holder.title.setText(dev.NickName);
                holder.info.setText(dev.UID);
                if (dev.n_gcm_count == 0) {
                    holder.GCM_Prompt.setVisibility(View.GONE);
                } else {
                    holder.GCM_Prompt.setVisibility(View.VISIBLE);
                    holder.GCM_Prompt.setText(Integer.toString(dev.n_gcm_count));
                }

                holder.status.setText(dev.Status);

//				if (nShowMessageCount == 0) {
//					holder.status.setText(dev.Status);
//				} else {
//					holder.status.setText(dev.Status);// + " " + cam.gettempAvIndex());
//				}

                holder.eventLayout.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        MainActivity.this.selectedDevice = dev;
                        MainActivity.this.selectedCamera = cam;

                        initContextMenu();
                        iconContextMenu.createMenu("").show();
                    }
                });
            }

            return convertView;

        }

        public final class ViewHolder {
            public ImageView img;
            public TextView title;
            public TextView info;
            public TextView status;
            public TextView GCM_Prompt;
            public FrameLayout eventLayout;
        }
    }

    private class ResultStateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String result = intent.getStringExtra("dev_uid");
            if (result == null) {

            } else {
                for (int i = 0; i < DeviceList.size(); i++) {
                    if (DeviceList.get(i).UID.equals(intent.getStringExtra("dev_uid")) == true) {
                        DeviceList.get(i).n_gcm_count++;
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        }
    }

    class ThreadReconnect extends Thread {
        boolean stopCheck = true;
        Activity mActivity = null;
        Camera mReconnectCamera = null;
        DeviceInfo mReconnectDevice = null;

        public ThreadReconnect(Camera camera, DeviceInfo dev) {
            stopCheck = false;
//			mActivity  = activity;
            mReconnectCamera = camera;
            mReconnectDevice = dev;
        }

        public void run() {
            while (!stopCheck) {

                long endTime = System.currentTimeMillis();

                if (endTime - startTime > 30000) {

                    mReconnectCamera.disconnect();
                    mReconnectCamera.connect(mReconnectDevice.UID);
                    mReconnectCamera.start(Camera.DEFAULT_AV_CHANNEL, mReconnectDevice.View_Account, mReconnectDevice.View_Password);
                    mReconnectCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_DEVINFO_REQ,
                            AVIOCTRLDEFs.SMsgAVIoctrlDeviceInfoReq.parseContent());
                    mReconnectCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETSUPPORTSTREAM_REQ,
                            AVIOCTRLDEFs.SMsgAVIoctrlGetSupportStreamReq.parseContent());
                    mReconnectCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ,
                            AVIOCTRLDEFs.SMsgAVIoctrlGetAudioOutFormatReq.parseContent());
                    mReconnectCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL, AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GET_TIMEZONE_REQ,
                            AVIOCTRLDEFs.SMsgAVIoctrlTimeZone.parseContent());

                    stopCheck = true;
                }

            }
            ;
        }
    }

}